package user

import (
	"context"

	"mall/common/errorx"
	"mall/common/jwtx"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/rpc/backendclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateUserLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateUserLogic {
	return &UpdateUserLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateUserLogic) UpdateUser(req *types.UpdateUserRequest) (*types.UpdateUserResponse, error) {
	if req.Id == 0 {
		return nil, errorx.Error(errorx.ERROR_USER_ID_REQUIRED, "")
	}

	adminId, _ := jwtx.GetUserId(l.ctx)

	_, err := l.svcCtx.BackendRpc.BackendUpdateUser(l.ctx, &backendclient.UpdateUserRequest{
		Id:        req.Id,
		Username:  req.Username,
		Nickname:  req.Nickname,
		Name:      req.Name,
		Email:     req.Email,
		Mobile:    req.Mobile,
		Status:    req.Status,
		DeptId:    req.DeptId,
		RoleId:    req.RoleId,
		UpdatedBy: adminId,
	})
	if err != nil {
		return nil, err
	}

	return &types.UpdateUserResponse{
		Status:  "ok",
		Message: "更新用户成功",
	}, nil
}
